﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ELS.Template.DragContent;
using System.Data.SqlClient;
using ELS.User;

namespace ELS.Template
{
    public partial class AddEditQuestionForm : Form
    {
        Panel parentPanel;
        TextBox textBox;
        PictureBox pictureBox;

        //Show shadow of the drop target
        Boolean shadowVisible = false;

        public String templateName = "";
        public int templateId = -1;
        private int categoryId = -1;
        private int questionId = -1;

        DropShadow shadow = new DropShadow();

        bool isNew = true;

        //Dragged control in template
        Control draggedControl = null;

        //Question data
        String mQuestion = "";

        TemplateController templateController = new TemplateController();

        public AddEditQuestionForm(TextBox textBox, PictureBox pictureBox, Panel pnlTemplateForm)
        {
            this.textBox = textBox;
            this.pictureBox = pictureBox;            
            parentPanel = pnlTemplateForm;
            
            InitializeComponent();

            //Allow drag & drop on this form
            dropFlowLayout.AllowDrop = true;
            //Set default
            //questionText.Text = Utils.Utils.DEFAULT_QUESTION_TEXT;
            //Template name
            templateNameLabel.Text = templateName;
            
        }

        //private void AddEditQuestionForm_Load(object sender, EventArgs e)
        //{
        //    //Allow drag & drop on this form
        //    dropFlowLayout.AllowDrop = true;
        //    //Set default
        //    questionText.Text = Utils.Utils.DEFAULT_QUESTION_TEXT;
        //    //Template name
        //    templateNameLabel.Text = templateName;
        //}   

        private void dropFlowLayout_DragDrop(object sender, DragEventArgs e)
        {
            //Get shadow position
            int index = dropFlowLayout.Controls.GetChildIndex(shadow, false);

            //Remove drag target shadow
            removeShadow();

            //If user was re-arrange controls
            if (draggedControl != null)
            {
                //Add item to layout
                this.dropFlowLayout.Controls.Add(draggedControl);

                //Move item to previous shadow location
                this.dropFlowLayout.Controls.SetChildIndex(draggedControl, index);

                draggedControl = null;
            }
            else
            {

                DragInterface item = null;
                if (e.Data.GetDataPresent(typeof(RadioItemTag)))
                {
                    item = (DragInterface)e.Data.GetData(typeof(RadioItemTag));
                }
                else if (e.Data.GetDataPresent(typeof(ValueItemTag)))
                {
                    item = (DragInterface)e.Data.GetData(typeof(ValueItemTag));
                }
                else if (e.Data.GetDataPresent(typeof(CheckItemTag)))
                {
                    item = (DragInterface)e.Data.GetData(typeof(CheckItemTag));
                }

                else
                {
                    //The item was not supported
                    return;
                }

                //Do nothing if we drag an item and drop at another position in the template
                if (item.isInTemplate())
                    return;

                //Clone the object
                UserControl newItem = item.makeNewObject();

                //And add to the template
                int fixWidth = dropFlowLayout.Width - dropFlowLayout.Padding.All * 2 - 45;
                newItem.MinimumSize = new Size(fixWidth, newItem.Height);
                newItem.MaximumSize = new Size(fixWidth, 0);

                //newItem.Margin = new Padding(15);

                //Add item to layout
                this.dropFlowLayout.Controls.Add(newItem);

                //Move item to previous shadow location
                this.dropFlowLayout.Controls.SetChildIndex(newItem, index);
            }
        }

        private void showShadow(int x, int y)
        {
            //Add shadow if it's not visible
            if (!shadowVisible)
            {
                shadowVisible = true;
                shadow.Width = dropFlowLayout.Width - dropFlowLayout.Padding.All * 2 - 41;
                shadow.Height = 50;
                this.dropFlowLayout.Controls.Add(shadow);
            }

            //Put shadow to correct position
            Point p = dropFlowLayout.PointToClient(new Point(x, y));
            var item = dropFlowLayout.GetChildAtPoint(p);

            //No need to update shadow if it's already below drag position
            if (shadow.Equals(item)) return;

            int index = dropFlowLayout.Controls.GetChildIndex(item, false);

            if (index == 0)
            {
                index = 1;
                if ((dropFlowLayout.Controls.Count > 1) && (shadow.Equals(dropFlowLayout.Controls[index])))
                {
                    //Shadow is at correct position
                    return;
                }
            }
            else
                if (item != null)
                {
                    if (item.PointToClient(new Point(x, y)).Y > 50)
                    {
                        index++;
                    }
                }



            this.dropFlowLayout.Controls.Add(shadow);
            dropFlowLayout.Controls.SetChildIndex(shadow, index);
        }

        //Hide shadow if it's visible
        private void removeShadow()
        {
            if (shadowVisible)
            {
                shadowVisible = false;
                dropFlowLayout.Controls.Remove(shadow);
            }
        }

        private void disableAllItems()
        {
            for (int i = 0; i < dropFlowLayout.Controls.Count; i++)
            {
                try
                {

                    DragInterface item = (DragInterface)dropFlowLayout.Controls[i];
                    //item.disableControls();
                }
                catch (Exception)
                {
                }
            }
        }

        private void dropFlowLayout_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;

            DragInterface item = null;
            if (e.Data.GetDataPresent(typeof(RadioItemTag)))
            {
                item = (DragInterface)e.Data.GetData(typeof(RadioItemTag));
            }
            else if (e.Data.GetDataPresent(typeof(RadioItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(RadioItem));
            }
            else if (e.Data.GetDataPresent(typeof(CheckItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(CheckItem));
            }
            else if (e.Data.GetDataPresent(typeof(CheckItemTag)))
            {
                item = (DragInterface)e.Data.GetData(typeof(CheckItemTag));
            }
            else if (e.Data.GetDataPresent(typeof(ValueItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(ValueItem));
            }
            else if (e.Data.GetDataPresent(typeof(ValueItemTag)))
            {
                item = (DragInterface)e.Data.GetData(typeof(ValueItemTag));
            }
            else
            {
                //The item was not supported
                return;
            }

            //Re-arrange item if we drag an item and drop at another position in the template
            if (item.isInTemplate())
            {
                draggedControl = (Control)item;
                //lastPosition = dropFlowLayout.Controls.GetChildIndex(draggedControl);
                dropFlowLayout.Controls.Remove(draggedControl);
            }

            //Show drop target shadow
            showShadow(e.X, e.Y);
        }

        private void trashArea_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
            trashBitmap.Image = Properties.Resources.FullTrash_48x48x32;
        }

        //Drag to trash event
        private void trashArea_DragDrop(object sender, DragEventArgs e)
        {
            trashBitmap.Image = Properties.Resources.EmptyTrash_48x48x32;
            DragInterface item = null;
            if (e.Data.GetDataPresent(typeof(RadioItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(RadioItem));
            }
            else if (e.Data.GetDataPresent(typeof(CheckItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(CheckItem));
            }
            else if (e.Data.GetDataPresent(typeof(ValueItem)))
            {
                item = (DragInterface)e.Data.GetData(typeof(ValueItem));
            }

            //Drag unsupported item to trash bin
            if (item == null)
                return;

            //Unmark dragged control
            draggedControl = null;

            //Only delete item currently in template
            if (item.isInTemplate())
            {
                this.dropFlowLayout.Controls.Remove((UserControl)item);
            }
        }

        private void dependList_CheckedChanged(object sender, EventArgs e)
        {
            //Show depend list if checked
            if (dependList.Checked)
            {
                QuestionDependentListForm dependForm = new QuestionDependentListForm();
                dependForm.ShowDialog();
            }
        }

        //Save data to database
        private int saveCurrentQuestion()
        {
            if (isNew)
            {// Save new question
                categoryId = -1;
                questionId = -1;

                //Save question category info                
                if (templateCategoryTitle.Text.Trim().Length == 0)
                { // Default single category
                    categoryId = templateController.InsertCategory(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE, Utils.Utils.QUESTION_CATEGORY_DEFAULT_DESCRIPTION);
                    //  Save relationship between template document and category
                    if (categoryId > 0) {
                        templateController.InsertDocumentCategoryRelationship(templateId, categoryId, 1);
                    }
                }
                else
                {
                    categoryId = templateController.GetCategoryIdByTitle(templateCategoryTitle.Text.Trim(), templateId);
                    if (categoryId < 0)
                    {
                        categoryId = templateController.InsertCategory(templateCategoryTitle.Text.Trim(), templateCategoryTitle.Text.Trim());
                        //  Save relationship between template document and category
                        if (categoryId > 0)
                        {
                            templateController.InsertDocumentCategoryRelationship(templateId, categoryId, 1);
                        }
                    }
                }

                if (categoryId > 0)
                {
                    // Save question info
                    questionId = templateController.InsertQuestion(mQuestion, questionNoTextBox.Text.Trim(), 1);

                    if (questionId > 0)
                    {
                        // Save relationship between question and question category
                        templateController.InsertCategoryQuestionRelationship(categoryId, questionId, 1);

                        // Save answer info
                        List<int> listAnswer = new List<int>();
                        foreach (Control uc in dropFlowLayout.Controls)
                        {
                            RadioItem ri = uc as RadioItem;
                            CheckItem ci = uc as CheckItem;
                            ValueItem vi = uc as ValueItem;
                            int answerId = -1;
                            int answerTypeId = -1;
                            if (ri != null && ri.mContent.Trim().Length > 0)
                            {
                                if (ri.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_RADIO_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_RADIO;
                                }
                                answerId = templateController.InsertAnswer(ri.mContent.Trim(), answerTypeId);
                            }
                            else if (ci != null && ci.mContent.Trim().Length > 0)
                            {
                                if (ci.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_CHECK_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_CHECK;
                                }
                                answerId = templateController.InsertAnswer(ci.mContent.Trim(), answerTypeId);
                            }
                            else if (vi != null && vi.mContent.Trim().Length > 0)
                            {
                                if (vi.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_VALUE_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_VALUE;
                                }
                                answerId = templateController.InsertAnswer(vi.mContent.Trim(), answerTypeId);
                            }

                            if (answerId > 0)
                            {
                                listAnswer.Add(answerId);
                            }
                        }

                        // Save relationship between question and answer
                        for (int i = 0; i < listAnswer.Count; i++)
                        {
                            templateController.InsertQuestionAnswerRelationship(questionId, listAnswer[i], i + 1);
                        }
                    }
                }
            }
            else { // Update old question
                string oldCategoryTitle = templateController.GetCurrentCategoryTitleByQuestionId(questionId, templateId);
                string previousQuestionCategoryTitle = templateController.GetPreviousQuestionCategoryTitleByCurrentQuestionId(questionId, templateId);// get category content of previous question
                string nextQuestionCategoryTitle = templateController.GetNextQuestionCategoryTitleByCurrentQuestionId(questionId, templateId);// get category content of next question

                if (previousQuestionCategoryTitle.Length == 0)
                { // Update first question
                    if ((templateCategoryTitle.Text.Trim().Length == 0 
                                || templateCategoryTitle.Text.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)) 
                            && !oldCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE))
                    { // Update from customize category content => default category content
                        categoryId = templateController.GetCategoryIdByQuestionId(questionId, templateId);
                        if (categoryId > 0)
                        {
                            templateController.UpdateCategoryInfo(categoryId, Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE, Utils.Utils.QUESTION_CATEGORY_DEFAULT_DESCRIPTION);
                        }
                    }
                    else if(templateCategoryTitle.Text.Trim().Length > 0 
                        && !templateCategoryTitle.Text.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                        && !templateCategoryTitle.Text.Trim().Equals(oldCategoryTitle))
                    { // Update customize category content => other customize category content
                        bool isCategoryExistedInDocument = templateController.IsCategoryExistedInDocument(templateCategoryTitle.Text.Trim(), templateId);
                        if(!isCategoryExistedInDocument)
                        {                       
                            categoryId = templateController.GetCategoryIdByQuestionId(questionId, templateId);
                            if (categoryId > 0)
                            {
                                templateController.UpdateCategoryInfo(categoryId, templateCategoryTitle.Text.Trim(), templateCategoryTitle.Text.Trim());
                            }
                        }
                    }
                }
                else if(previousQuestionCategoryTitle.Length > 0 && nextQuestionCategoryTitle.Length > 0)
                { // Update middle question

                }
                else if (nextQuestionCategoryTitle.Length == 0) 
                { // Update last question 
                
                }
                if (templateCategoryTitle.Text.Trim().Length > 0
                    && !templateCategoryTitle.Text.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                    && !templateCategoryTitle.Text.Trim().Equals(oldCategoryTitle)) {
                    // Updated to new content
                        if (!oldCategoryTitle.Equals(previousQuestionCategoryTitle) 
                            && previousQuestionCategoryTitle.Length > 0
                            && !previousQuestionCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                            && templateCategoryTitle.Text.Trim().Equals(previousQuestionCategoryTitle)) {
                            // Remove old relationship between category and question
                            categoryId = templateController.GetCategoryIdByTitle(oldCategoryTitle, templateId);
                            if (categoryId > 0)
                            {
                                templateController.RemoveCategoryQuestionRelationship(categoryId, questionId);
                            }
                            // Save new relationship between category and question
                            categoryId = templateController.GetCategoryIdByTitle(previousQuestionCategoryTitle, templateId);
                            if (categoryId > 0)
                            {
                                templateController.InsertCategoryQuestionRelationship(categoryId, questionId, 1);
                            }
                        }
                    }
                else if (templateCategoryTitle.Text.Trim().Length == 0 
                    || templateCategoryTitle.Text.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)) { 
                    // Updated to default content
                    if (!oldCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                        && (!previousQuestionCategoryTitle.Equals(nextQuestionCategoryTitle) 
                        || (previousQuestionCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE) 
                            && nextQuestionCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE))))
                    { 
                    
                    }
                }

                if(!templateCategoryTitle.Text.Trim().Equals(oldCategoryTitle)){// Category content for this question is updated
                    string previousQuestionCategoryTitle = templateController.GetPreviousCategoryTitleByQuestionId(questionId);// get category content of previous question
                    string nextQuestionCategoryTitle = templateController.GetNextCategoryTitleByQuestionId(questionId);// get category content of next question
                    if (templateCategoryTitle.Text.Trim().Length == 0) { // Updated to default category                        
                        if (!previousQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE) 
                            && !nextQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                            && previousQuestionCategoryTitle.Trim().Equals(nextQuestionCategoryTitle.Trim()))
                        { //
                            
                        }
                    }
                }
                // Save question category info                
                if (templateCategoryTitle.Text.Trim().Length == 0)
                { // Default single category
                    categoryId = templateController.InsertCategory(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE, Utils.Utils.QUESTION_CATEGORY_DEFAULT_DESCRIPTION);
                }
                else
                {
                    categoryId = templateController.GetCategoryIdByTitle(templateCategoryTitle.Text.Trim(), templateId);
                    if (categoryId < 0)
                    {
                        categoryId = templateController.InsertCategory(templateCategoryTitle.Text.Trim(), templateCategoryTitle.Text.Trim());
                    }
                }

                if (categoryId > 0)
                {
                    // Save question info
                    questionId = templateController.InsertQuestion(mQuestion, questionNoTextBox.Text.Trim(), 1);

                    if (questionId > 0)
                    {
                        // Save relationship between question and question category
                        templateController.InsertCategoryQuestionRelationship(categoryId, questionId, 1);

                        // Save answer info
                        List<int> listAnswer = new List<int>();
                        foreach (Control uc in dropFlowLayout.Controls)
                        {
                            RadioItem ri = uc as RadioItem;
                            CheckItem ci = uc as CheckItem;
                            ValueItem vi = uc as ValueItem;
                            int answerId = -1;
                            int answerTypeId = -1;
                            if (ri != null && ri.mContent.Trim().Length > 0)
                            {
                                if (ri.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_RADIO_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_RADIO;
                                }
                                answerId = templateController.InsertAnswer(ri.mContent.Trim(), answerTypeId);
                            }
                            else if (ci != null && ci.mContent.Trim().Length > 0)
                            {
                                if (ci.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_CHECK_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_CHECK;
                                }
                                answerId = templateController.InsertAnswer(ci.mContent.Trim(), answerTypeId);
                            }
                            else if (vi != null && vi.mContent.Trim().Length > 0)
                            {
                                if (vi.mAllowComment)
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_VALUE_COMMENT;
                                }
                                else
                                {
                                    answerTypeId = Utils.Utils.ANSWER_TYPE_VALUE;
                                }
                                answerId = templateController.InsertAnswer(vi.mContent.Trim(), answerTypeId);
                            }

                            if (answerId > 0)
                            {
                                listAnswer.Add(answerId);
                            }
                        }

                        // Save relationship between question and answer
                        for (int i = 0; i < listAnswer.Count; i++)
                        {
                            templateController.InsertQuestionAnswerRelationship(questionId, listAnswer[i], i + 1);
                        }
                    }
                }
            }
            return questionId;
        }

        private void clearCurrentForm()
        {
            String currentTemplateName = templateName;
            int currentTemplateId = templateId;

            foreach (Control ctl in parentPanel.Controls)
            {
                ctl.Dispose();
            }

            AddEditQuestionForm addEditTemplateForm = new AddEditQuestionForm(textBox, pictureBox, parentPanel);
            addEditTemplateForm.TopLevel = false;
            addEditTemplateForm.Parent = parentPanel;
            addEditTemplateForm.templateName = currentTemplateName;
            addEditTemplateForm.templateId = currentTemplateId;
            addEditTemplateForm.questionId = -1;
            addEditTemplateForm.Visible = true;
            addEditTemplateForm.isNew = true;
            questionTextInput.Hide();
            questionText.Show();
        }

        private void LoadTemplateQuestionInfo(TemplateQuestion tq) {
            String currentTemplateName = templateName;
            int currentTemplateId = templateId;

            foreach (Control ctl in parentPanel.Controls)
            {
                ctl.Dispose();
            }

            AddEditQuestionForm addEditTemplateForm = new AddEditQuestionForm(textBox, pictureBox, parentPanel);
            addEditTemplateForm.TopLevel = false;
            addEditTemplateForm.Parent = parentPanel;
            addEditTemplateForm.templateName = currentTemplateName;
            addEditTemplateForm.templateId = currentTemplateId;
            addEditTemplateForm.questionId = int.Parse(tq.Id);
            mQuestion = tq.Content;
            addEditTemplateForm.questionText.Text = tq.Content;
            addEditTemplateForm.questionTextInput.Text = tq.Content;
            questionTextInput.Hide();
            questionText.Show();
            addEditTemplateForm.questionNoTextBox.Text = tq.QuestionNo;
            addEditTemplateForm.isNew = false;

            //Load answer information
            List<TemplateAnswer> listAnswers = templateController.GetAnswersByQuestionId(tq.Id);
           
            for (int i = 0; i < listAnswers.Count; i++) {
                switch (int.Parse(listAnswers[i].AnswerTypeId)) { 
                    case Utils.Utils.ANSWER_TYPE_CHECK:
                        CheckItem ci = new CheckItem();

                        //And add to the template
                        int ciFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        ci.MinimumSize = new Size(ciFixWidth, ci.Height);
                        ci.MaximumSize = new Size(ciFixWidth, 0);
                        ci.setContent(listAnswers[i].Content, false);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)ci);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)ci, i+1);
                        break;
                    case Utils.Utils.ANSWER_TYPE_CHECK_COMMENT:
                        //Clone the object
                        CheckItem cic = new CheckItem();

                        //And add to the template
                        int cicFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        cic.MinimumSize = new Size(cicFixWidth, cic.Height);
                        cic.MaximumSize = new Size(cicFixWidth, 0);
                        cic.setContent(listAnswers[i].Content, true);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)cic);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)cic, i + 1);
                        break;
                    case Utils.Utils.ANSWER_TYPE_RADIO:
                        RadioItem ri = new RadioItem();

                        //And add to the template
                        int riFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        ri.MinimumSize = new Size(riFixWidth, ri.Height);
                        ri.MaximumSize = new Size(riFixWidth, 0);
                        ri.setContent(listAnswers[i].Content, false);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)ri);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)ri, i + 1);
                        break;
                    case Utils.Utils.ANSWER_TYPE_RADIO_COMMENT:
                        RadioItem ric = new RadioItem();

                        //And add to the template
                        int ricFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        ric.MinimumSize = new Size(ricFixWidth, ric.Height);
                        ric.MaximumSize = new Size(ricFixWidth, 0);
                        ric.setContent(listAnswers[i].Content, true);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)ric);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)ric, i + 1);
                        break;
                    case Utils.Utils.ANSWER_TYPE_VALUE:
                        ValueItem vi = new ValueItem();

                        //And add to the template
                        int viFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        vi.MinimumSize = new Size(viFixWidth, vi.Height);
                        vi.MaximumSize = new Size(viFixWidth, 0);
                        vi.setContent(listAnswers[i].Content, false);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)vi);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)vi, i + 1);
                        break;
                    case Utils.Utils.ANSWER_TYPE_VALUE_COMMENT:
                        ValueItem vic = new ValueItem();

                        //And add to the template
                        int vicFixWidth = addEditTemplateForm.dropFlowLayout.Width - addEditTemplateForm.dropFlowLayout.Padding.All * 2 - 45;
                        vic.MinimumSize = new Size(vicFixWidth, vic.Height);
                        vic.MaximumSize = new Size(vicFixWidth, 0);
                        vic.setContent(listAnswers[i].Content, true);
                        //newItem.Margin = new Padding(15);

                        //Add item to layout
                        addEditTemplateForm.dropFlowLayout.Controls.Add((UserControl)vic);

                        //Move item to previous shadow location
                        addEditTemplateForm.dropFlowLayout.Controls.SetChildIndex((UserControl)vic, i + 1);
                        break;

                }                
            }
            addEditTemplateForm.Visible = true;

        }

        private void LoadPreviousQuestion(int currentQuestionId)
        {
            TemplateQuestion tq = templateController.GetPreviousQuestion(currentQuestionId);
            if (int.Parse(tq.Id) > 0)
            {
                LoadTemplateQuestionInfo(tq);
            } else {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_DoNotHavePreviousQuestion, UserCommon.WARNING_STATUS);
            }
        }

        private void LoadNextQuestion(int currentQuestionId)
        {
            TemplateQuestion tq = templateController.GetNextQuestion(currentQuestionId);
            if (int.Parse(tq.Id) > 0)
            {
                LoadTemplateQuestionInfo(tq);
            }
            else
            {
                clearCurrentForm();
            }
        }

        private void previousButton_Click(object sender, EventArgs e)
        {
            if (isCorrectQuestionInfo())
            {
                int currentQuestionId = saveCurrentQuestion();
                if (currentQuestionId > 0) {
                    LoadPreviousQuestion(currentQuestionId);
                }
            }
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            if (isCorrectQuestionInfo())
            {
                int currentQuestionId = saveCurrentQuestion();
                if (currentQuestionId > 0)
                {
                    LoadNextQuestion(currentQuestionId);
                }
            }
        }

        private bool isCorrectQuestionInfo() {
            // Validate question no
            if (questionNoTextBox.Text.Trim().Length == 0) {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_DoNotEnterQuestionNo, UserCommon.WARNING_STATUS);
                return false;
            }

            // Validate question category
            if (!isNew)
            {// Only validate in case update question
                string oldCategoryTitle = templateController.GetCategoryTitleByQuestionId(questionId);
                if (!oldCategoryTitle.Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE) && !templateCategoryTitle.Text.Trim().Equals(oldCategoryTitle))
                {// Category content for this question is updated
                    string previousQuestionCategoryTitle = templateController.GetPreviousCategoryTitleByQuestionId(questionId);// get category content of previous question
                    string nextQuestionCategoryTitle = templateController.GetNextCategoryTitleByQuestionId(questionId);// get category content of next question
                    if (templateCategoryTitle.Text.Trim().Length == 0 
                        || templateCategoryTitle.Text.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE))
                    { // Updated to default category                        
                        if (!previousQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                            && !nextQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                            && previousQuestionCategoryTitle.Trim().Equals(nextQuestionCategoryTitle.Trim()))
                        { //
                            UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_CanNotUpdateCategoryForMiddleQuestion, UserCommon.WARNING_STATUS);
                            return false;
                        }
                    }
                    else { // Updated to other category content
                        if (!previousQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE)
                            && !nextQuestionCategoryTitle.Trim().Equals(Utils.Utils.QUESTION_CATEGORY_DEFAULT_TITLE))
                        {
                            if (previousQuestionCategoryTitle.Trim().Equals(nextQuestionCategoryTitle.Trim()))
                            { //
                                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_CanNotUpdateCategoryForMiddleQuestion, UserCommon.WARNING_STATUS);
                                return false;
                            }
                            else if (!templateCategoryTitle.Text.Trim().Equals(previousQuestionCategoryTitle.Trim()))
                            {
                                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_CanNotUpdateCategoryDiffContentWithPreviousQuestion, UserCommon.WARNING_STATUS);
                                return false;
                            }
                        }
                    }
                }
            }

            if (questionTextInput.Text.Trim().Length == 0) {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_DoNotEnterContent, UserCommon.WARNING_STATUS);
                return false;
            }

            int counter = 0;
            foreach (Control uc in dropFlowLayout.Controls) {
                RadioItem ri = uc as RadioItem;
                CheckItem ci = uc as CheckItem;
                ValueItem vi = uc as ValueItem;
                if (ri != null || ci != null || vi != null) {                    
                    if ((ri != null && ri.mContent.Trim().Length == 0) 
                        || (ci != null && ci.mContent.Trim().Length == 0)
                        || (vi != null && vi.mContent.Trim().Length == 0))
                    {
                        UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_DoNotHaveContentForAnswer, UserCommon.WARNING_STATUS);
                        return false;
                    }
                    counter++;
                }
            }
            if (counter == 0) {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.AddEditQuestion_DoNotHaveAnyAnswer, UserCommon.WARNING_STATUS);
                return false;
            }
            return true;
        }

        private void dropFlowLayout_DragLeave(object sender, EventArgs e)
        {
            if (draggedControl != null)
            {

            }
            removeShadow();
        }

        private void dropFlowLayout_MouseMove(object sender, MouseEventArgs e)
        {
            if (shadowVisible)
            {
                //Show drop target shadow
                showShadow(e.X, e.Y);
            }
        }

        private void dropFlowLayout_DragOver(object sender, DragEventArgs e)
        {
            if (shadowVisible)
            {
                //Show drop target shadow
                showShadow(e.X, e.Y);
            }
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            trashBitmap.Image = Properties.Resources.FullTrash_48x48x32;
        }

        private void trashArea_DragLeave(object sender, EventArgs e)
        {
            trashBitmap.Image = Properties.Resources.EmptyTrash_48x48x32;
        }

        private void trashArea_Paint(object sender, PaintEventArgs e)
        {

        }

        private void questionText_Click(object sender, EventArgs e)
        {
            /*
            QuestionInputForm inputForm = new QuestionInputForm();
            inputForm.questionBox.Text = mQuestion;
            DialogResult result = inputForm.ShowDialog(this);
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                setQuestionText(inputForm.questionBox.Text);
            }
            inputForm.Dispose();
             */
            questionText.Hide();
            questionTextInput.Show();
            //questionTextInput.Text = mQuestion;
            questionTextInput.Focus();
            questionTextInput.Size = questionText.Size;

            // CanhBX add scrollbar START
            questionTextInput.ScrollBars = ScrollBars.Vertical;
            // CanhBX add scrollbar END            
        }

        public void setQuestionText(String question)
        {
            // CanhBX comment out START
            //int diff = questionPanel.Height - questionText.Height;
            //questionText.MaximumSize = new Size(questionText.Width, 110);
            //questionText.MinimumSize = new Size(questionText.Width, 110);
            //questionText.AutoSize = true;
            // CanhBX comment out END

            if ((question == null) || (question.Equals("")))
            {
                mQuestion = null;
                questionText.Text = Utils.Utils.DEFAULT_QUESTION_TEXT;
                questionText.ForeColor = Color.Red;
                questionText.TextAlign = ContentAlignment.MiddleCenter;
            }
            else
            {
                mQuestion = question;
                questionText.Text = mQuestion;
                questionText.ForeColor = Color.Black;
                questionText.TextAlign = ContentAlignment.MiddleLeft;
            }

            // CanhBX comment out START
            //questionPanel.Height = questionText.Height + diff;
            // CanhBX comment out END
        }

        private void questionText_MouseEnter(object sender, EventArgs e)
        {
            if (questionText.Visible)
            {
                questionText.BackColor = Color.LightGray;
            }
        }

        private void questionText_MouseLeave(object sender, EventArgs e)
        {
            if (questionText.Visible)
            {
                questionText.BackColor = Color.White;
            }
        }

        private void questionTextInput_Leave(object sender, EventArgs e)
        {
            mQuestion = questionTextInput.Text;
            setQuestionText(questionTextInput.Text);
            questionTextInput.Hide();
            questionText.Show();
        }

        private void templateListButton_Click(object sender, EventArgs e)
        {
            foreach (Control ctl in parentPanel.Controls)
            {
                ctl.Dispose();
            }

            ELS.Template.ListTemplateForm listUserFrm = new ELS.Template.ListTemplateForm(textBox, pictureBox, parentPanel);
            listUserFrm.TopLevel = false;
            listUserFrm.Parent = parentPanel;
            listUserFrm.Visible = true;
        }
         
    }
}
